<template>
    <div class="banner-container" @mouseover="autoStop" @mouseleave="autoStart">
        <!-- 要轮播的图片 -->
        <ul class="images" :style="{ 
            width: banners.length * 100 + '%', 
            marginLeft: -index * 100 + '%'
        }">
            <li v-for="(item, i) in banners" :key="i" class="image">
                <a :href="item.url">
                    <img :src="item.image" :alt="item.title" :title="item.title"/>
                    <span class="title">{{ item.title }}</span>
                </a>
            </li>
        </ul>
        <!-- 指示符 -->
        <ul class="dots">
            <li v-for="(item, i) in banners" :key="i" :class="{ active: i === index }" @click="index = i"></li>
        </ul>
    </div>
</template>

<script>
export default {
    props:{
        banners: {
            type: Array,    // 属性类型是数组
            required: true  // 必须要传递该属性
        },
        duration: {
            type: Number,
            default: 2000
        }
    },
    data() {
        return {
            index: 0,    // 表示当前显示的是第几张图片
            timer: null
        }
    },
    methods: {
		// 开始自动轮播
		autoStart() {
			if (this.timer !== null) return;
			this.timer = window.setInterval(() => {
				this.index = (this.index + 1) % this.banners.length;
			}, this.duration);
		},
		// 停止自动轮播
		autoStop() {
			window.clearInterval(this.timer);
			this.timer = null;
		}
	},
	created() {
		this.autoStart();
	},
	destroyed() {
		this.autoStop();
	}
}
</script>

<style scoped>
.banner-container {
    width: 100%;
    overflow: hidden;
    position: relative;
    margin-top: 10px;
}
ul {
    padding: 0;
    list-style: none;
}
ul li {
    display: inline-block;
    cursor: pointer;
}
ul.images {
    transition: 0.5s;
    font-size: 0;
    display: flex;
}
.images img {
    width: 1140px;
    height: 100%;
    height: 500px;
    object-fit: cover;
}
.image {
    position: relative;
}
.image span {
    position: absolute;
    left: 0;
    bottom: 0;
    font-size: 16px;
    color: #fff;
    display: inline-block;
    width: 80%;
    padding: 17px 0;
    padding-left: 20px;
    background: linear-gradient(to bottom, transparent, #000);
}

/* 指示符样式 */
.dots {
    position: absolute;
    bottom: 10px;
    right: 20px;
}
.dots li {
    width: 10px;
    height: 10px;
    border-radius: 50%;
    border: 2px solid #ffffff;
    margin: 5px;
    background-color: #ffffff;
}
.dots li.active {
    background-color: #000;
}
</style>